<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统</title>
    <!-- 引入外部资源 -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/http-vue-loader"></script>
    <script src="https://unpkg.com/@element-plus/icons-vue"></script>
</head>
<body>
<!-- Vue应用挂载点 -->
<div id="app" style="height: 100vh;"></div>

<script>
    // 初始化Vue相关对象
    const { createApp } = Vue;
    const { createRouter, createWebHistory } = VueRouter;
    const { ElMessage, ElMessageBox } = ElementPlus;
    const { useRouter } = VueRouter;

    // 路由配置 - 映射路径与组件
    const router = createRouter({
        history: createWebHistory(), // 使用HTML5历史模式（无#号）
        routes: [
            { path: '/', redirect: '/login' }, // 默认重定向到登录页
            {
                path: '/login',
                name: 'Login',
                component: () => httpVueLoader('./components/Login.vue')
            },
            {
                path: '/home',
                name: 'Home',
                component: () => httpVueLoader('./components/Home.vue'),
                meta: { requiresAuth: true } // 需要登录才能访问
            },
            {
                path: '/books',
                name: 'BookManage',
                component: () => httpVueLoader('./components/BookManage.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: '/staff',
                name: 'StaffManage',
                component: () => httpVueLoader('./components/StaffManage.vue'),
                meta: { requiresAuth: true }
            }
        ]
    });

    // 路由守卫 - 未登录用户拦截
    router.beforeEach((to, from, next) => {
        // 判断当前路由是否需要认证
        if (to.meta.requiresAuth) {
            // 检查本地存储中是否有Token
            const token = localStorage.getItem('library_token');
            if (!token) {
                ElMessage.warning('请先登录系统！');
                next('/login'); // 未登录，重定向到登录页
                return;
            }
        }
        next(); // 已登录或无需认证，正常访问
    });

    // Axios全局配置 - 请求拦截器（添加Token）
    axios.interceptors.request.use(
        (config) => {
            // 从本地存储获取Token并添加到请求头
            const token = localStorage.getItem('library_token');
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
            // 设置后端API基础路径（与后端Controller@RequestMapping保持一致）
            config.baseURL = '/api';
            return config;
        },
        (error) => Promise.reject(error)
    );

    // Axios响应拦截器（处理错误和Token过期）
    axios.interceptors.response.use(
        (response) => {
            // 直接返回响应数据体（简化前端处理）
            return response.data;
        },
        (error) => {
            // 处理401未授权错误（Token过期或无效）
            if (error.response && error.response.status === 401) {
                localStorage.removeItem('library_token');
                localStorage.removeItem('library_user');
                ElMessage.error('登录已过期，请重新登录！');
                router.push('/login');
            }
            return Promise.reject(error);
        }
    );

    // 创建Vue应用实例
    const app = createApp({});

    // 全局注册Element Plus组件和图标
    for (const [key, component] of Object.entries(ElementPlus)) {
        app.component(key, component);
    }
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }

    // 全局挂载工具方法和属性
    app.config.globalProperties.$axios = axios;
    app.config.globalProperties.$message = ElMessage;
    app.config.globalProperties.$confirm = ElMessageBox.confirm;
    app.config.globalProperties.$router = router;

    // 应用路由并挂载到DOM
    app.use(router);
    app.mount('#app');
</script>
</body>
</html>
